package sandbox;

import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import java.io.*;
import java.util.ArrayList;


/**
 * Created by Sergii on 3/16/14.
 */
public class CheckStringsInFileAreInOrder {

    private static final String FILE_NAME = "file_to_test.txt";
    private static final String TEST_INPUT_STRING =
            "gshndgfvhsd 10 sdkhfjsdkf \n" +
            "hjhhhereeh 1 hhhdhgf \n"+
            "oiyuuiyhoiuyui 90 kugkjygjkygy \n";

    @BeforeTest
    public void createFileWithStrings() throws IOException {
        String content = TEST_INPUT_STRING;
        File file = new File(FILE_NAME);

        // if file doesnt exists, then create it
        if (!file.exists()){
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println(file.getName()+ " was created!");
    }

    @Test
    public void checkTheStringsAreSortedByNumber(){
        ArrayList<Integer> arrayList = new ArrayList<Integer>(0);
        BufferedReader br = null;
        try{
            String sCurrentLine;
            br = new BufferedReader(new FileReader(FILE_NAME));

            while ((sCurrentLine = br.readLine()) != null){
                String substring = sCurrentLine.replaceAll("\\D+", "");
                System.out.printf("Current string: %s   Extracted value: %s \n", sCurrentLine, substring);
                arrayList.add(Integer.parseInt(substring));
            }
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if (br != null)br.close();
            } catch (IOException ex){
                ex.printStackTrace();
            }
        }

        boolean arrayListIsSorted = true;

        for (int i = 1; i<arrayList.size();i++){
            if (arrayList.get(i-1).compareTo(arrayList.get(i))>0){
                arrayListIsSorted = false;
                break;
            }
        }
        Assert.assertTrue(arrayListIsSorted, "Lines are not sorted in order!");

    }
    @AfterTest
    public void deleteTestFile(){
        try {
            File file = new File (FILE_NAME);
            if (file.delete()){
                System.out.println(file.getName()+ " was deleted!");
            }else{
                System.out.println("Delete operation failed!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
